let _vue = null;
export default class VueRouter {
  static install(Vue) {
    if (VueRouter.install.installed) return;
    VueRouter.install.installed = true;
    // 把Vue的构造函数记录在全局
    _vue = Vue;

    // 把创建Vue的实例传入的router对象注入到Vue实例
    _vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _vue.prototype.$router = this.$options.router;
        }
      }
    })
  }

  constructor({ mode = 'hash', ...rest }) {
    this.options = { ...rest, mode };
    this.routeMap = {};
    this.data = _vue.observable({
      current: '/'
    });
    if (mode === 'hash' && !location.hash) { // 如果是hash模式，初始化hash为'/'
      location.hash = '/';
    }
    this.init();
  }

  init() {
    this.createRouteMap();
    this.initComponent(_vue);
    this.initEvent();
  }

  createRouteMap() {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component;
    });
  }

  initComponent(Vue) {
    const { options: { mode }, routeMap, data } = this;
    Vue.component('router-link', {
      props: {
        to: String
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler(e) {
          if (mode === 'hash') {
            location.hash = this.to;
          } else if (mode === 'history') {
            history.pushState({}, '', this.to);
          }
          e.preventDefault()
        }
      }
    });
    Vue.component('router-view', {
      render(h) {
        const cm = routeMap[data.current.replace('#', '')];
        return h(cm);
      }
    })
  }
  initEvent() {
    const mode = this.options.mode;
    window.addEventListener(mode === 'hash' ? 'hashchange' : 'popstate', () => {
      const location = window.location;
      this.data.current = mode === "hash" ? location.hash : location.pathname;
    });
  }
}